package com.yishun.springboot.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.RequestGongWuShu.envMonitoring;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yinquan.util.DataUtil;
import com.yinquan.util.TimeUtil;
import com.yishun.springboot.httpclient.Post8806;
import com.yishun.springboot.mapper.RecordNumMapper;
import com.yishun.springboot.mapper.TspDetailedMapper;
import com.yishun.springboot.mapper.TspGetDataMapper;
import com.yishun.springboot.pojo.GenOneDataResults;
import com.yishun.springboot.pojo.GeneralRecordNumBeans;
import com.yishun.springboot.pojo.GeneralRequestModel;
import com.yishun.springboot.pojo.RequestGongWuShuTspBaseInfo;
import com.yishun.springboot.pojo.RequestGongWuShuTspRealTimeData;
import com.yishun.springboot.pojo.TspGetData;
import com.yishun.springboot.pojo.TspHaveDevCode;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@Component
public class GongWuSuTimedUploadTspService {

	@Autowired
	TspDetailedMapper tspDetailedMapper;

	@Autowired
	TspGetDataMapper tspGetDataMapper;

	// 记录成功提交到工务署的条数(记录类型：通用表通用类型)
	@Autowired
	RecordNumMapper recordNumMapper;

	// 这里咱们获取了dev_code 接着咱们通过这个dev_code去拿8806数据和拿本机的表数据发送到工务署是分开的两个定时任务！

	// 每5分钟输出一次
	/**
	 * openapi同款方法进行定数更新本机所保存的tsp数据，业务上1分钟一次（或者灵活变动吧），与推到工务署tsp实时数据的获取时间一样√ 本项目
	 * openapianother就不做重复的更新数据操作DAO了
	 */
	// @Async
	// @Scheduled(fixedRate = 1000 * 300)
	public void timingUpdateLocalTspData() {
		String timestamp = DataUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", new Date().getTime());
		// log.info("定时每60秒從8806処獲取tsp實時數據放進本地mysql，当前时间为：" + timestamp);

		Map map = new HashMap();// 用map裝結果集
		Post8806 p = new Post8806();
		GeneralRequestModel generalRequestModel = new GeneralRequestModel();// 请求集
		GenOneDataResults results = new GenOneDataResults(); // 结果集
		String temp = "";

		// 請求8806獲取實時數據
		generalRequestModel.setPageNumber(2); // 这个PageNumber写了暂时在Post8806暂时也没用上，后期优化
		generalRequestModel.setPageNumber(20);

		// 单个请求测试
		// List<TspHaveDevCode> td =
		// tspDetailedMapper.selectOne("44011130197369015P002587");
		//
		//
		// log.info("local:"+td.toString());
		//
		// generalRequestModel.setDeviceCode(td.get(0).getDevice_code());
		//
		// for (int i = 0; i < 11; i++) {
		//
		//
		// long startTime = System.currentTimeMillis();
		// results = p.AllRequest0086("/Yc/GetData", generalRequestModel);
		// long endTime = System.currentTimeMillis();
		// long usedTime = (endTime-startTime)/1000;
		// log.info("from 8806 to time use:"+usedTime+"second！");
		//
		// try {
		//
		// log.info("from 8806:"+results.getData());
		// } catch (Exception e) {
		// log.info("dsadsadsa");
		// continue;
		// // TODO: handle exception
		// }
		// }

		// 用了多长时间到8806，后续可能要判断超过多少秒的，就断了当前这个设备数据请求，进入下一个
		long startTime = 0l;
		long endTime = 0l;
		long usedTime = 0l;

		List<TspHaveDevCode> td = tspDetailedMapper.findAll();
		int j;
		String json = "";
		int recordNum = 0;

		for (int i = 0; i < td.size(); i++) {
			generalRequestModel.setDeviceCode(td.get(i).getDevice_code());
			temp = td.get(i).getDevice_code().toString();

			// map.put(temp, results.getData());
			try {
				startTime = System.currentTimeMillis();
				//
				results = p.AllRequest0086("/Yc/GetData", generalRequestModel);

				if (results == null)
					continue;

				endTime = System.currentTimeMillis();
				usedTime = (endTime - startTime) / 1000;
				if (usedTime > 5)
					// log.info("这个设备号所请求的8806数据，请求时间为："+usedTime+"秒！");

					if (results.getData() == null) {
						// log.info("这个设备号所请求的8806数据，Data为空："+temp);
						continue;
					}
			} catch (Exception e) {
				// log.info("这个设备号所请求的8806数据，出现了空异常："+temp);
				continue;
				// TODO: handle exception
			}

			try {
				// log.info("-------------------------------------");

				json = JSON.toJSONString(results.getData());
				TspGetData tspGetData = JSON.parseObject(json, TspGetData.class);
				int count = tspGetDataMapper.innerOneRecord(tspGetData);
				// if(count!=0)
				// log.info("插入本机扬尘监测设备数据完成。数据详细："+results.getData());
			} catch (Exception e) {

				recordNum++;
				// 这里做下日志
				// log.info("----------------------");
				// log.info("----------------------");
				// log.info("在8806那边传过来的数据为空！目前是已经出现的第 "+recordNum+" 条");
				// log.info("----------------------");
				// log.info("----------------------");
				continue;
			}

		}
		// log.info("已同步完成一批数据扬尘监测设备！ReCord update time："+DataUtil.currTime());

	}

	/**
	 * 推送本机tsp（扬尘监测）基本数据数据到工务署 √ --上报环境监测设备基本信息
	 * 后期可接入web接口，点击提交.在业务上这个接口device_code（设备号）所对应的扬尘监测设备只需要提交一次 全表推送到工务署
	 */
	public void UpdateGongWuShuTspMoreBaseData() {

		String timestamp = DataUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", new Date().getTime());
		log.info("定时输出，当前时间为：" + timestamp);

		List<TspHaveDevCode> l = tspDetailedMapper.findAll();

		for (int i = 0; i < l.size(); i++) {
			// if(i==0) {
			// log.info("first 1-0 we get some Device
			// code:"+l.get(i).getDevice_code());
			// log.info("first 1-1 we check some all select
			// string:"+l.get(i).toString());
			//
			// log.info("second 1-0 we according upthere select some devcode go
			// to get recently one article data.and insert to gongwushu");
			// log.info("this all --end!");
			// }
			// TspGetData tspGetData =
			// tspGetDataMapper.findOne(l.get(i).getDevice_code());
			// log.info("check in on upthere return
			// data:"+tspGetData.toString());
			RequestGongWuShuTspBaseInfo r = tspGetDataMapper.findRecentlyBaseInfoOneSendGWS(l.get(i).getDevice_code());
			log.info(r.toString());

			envMonitoring eM = new envMonitoring();
			eM.addBasicInfo(r);
		}

		log.info("初始化表格，插入基本数据信息完成！");

	}

	/**
	 * 推送本机tsp（扬尘监测）Web service接口 一条推送到工务署 第一步骤（共两步骤） 插入到本地mysql，自定义列对应插表
	 * 返回if条件条数。。自己看
	 */
	public String UpdateGongWuShuTspOneBaseDataOneStep(JSONObject jsonObject) {

		TspHaveDevCode tspHaveDevCode = new TspHaveDevCode();
		String device_code = (String) jsonObject.get("device_no");
		int count = tspDetailedMapper.selectCountOne(device_code);// 本方法判断return条件
		if (count == 0) {
			tspHaveDevCode.setDevice_code(device_code);
			tspHaveDevCode.setName((String) jsonObject.get("name"));
			tspHaveDevCode.setType((String) jsonObject.get("type"));
			tspHaveDevCode.setAddress((String) jsonObject.get("install_address"));
			tspHaveDevCode.setConstruction_sitename((String) jsonObject.get("install_company"));
			tspHaveDevCode.setInstall_date((String) jsonObject.get("device_installation_date"));
			tspHaveDevCode.setDevice_type_qiangji((String) jsonObject.get("device_type_qiangji"));
			tspHaveDevCode.setDevice_type_qiuji((String) jsonObject.get("device_type_qiuji"));

			tspDetailedMapper.innerOneRecord(tspHaveDevCode);

			return tspHaveDevCode.getDevice_code();
		} else {

			if (count == 1)
				return "1";
			if (count == 2)
				return "2";
		}
		return device_code + "这个device_code在表里竟然有三条以上的重复数据，赶紧放进log or catch记录记录！";

	}

	/**
	 * 推送本机tsp（扬尘监测）基本数据数据到工务署 √ 扬尘监测设备基本信息只需要、只能提交一次，dev_code唯一 一条推送到工务署
	 * 第二步骤（共两步骤） ，查表返回提交数据
	 */
	public String UpdateGongWuShuTspOneBaseDataTwoStep(String DeviceCode) {
		TspHaveDevCode tspHaveDevCode = tspDetailedMapper.selectOne(DeviceCode);

		RequestGongWuShuTspBaseInfo r = tspGetDataMapper.findRecentlyBaseInfoOneSendGWS(DeviceCode);
		log.info(r.toString());

		envMonitoring eM = new envMonitoring();
		String results = eM.addBasicInfo(r);
		return results;

	}

	/**
	 * 定时推送本机tsp实时数据到工务署（正常业务是10分钟一次） √ --本机tsp实时数据
	 */
	// @Scheduled(fixedRate = 1000 * 600)
	public void timingUpdateGongWuShuTspData() {

		log.info("进入定时推送本机tsp实时数据到工务署..。");
		String timestamp = DataUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", new Date().getTime());
		log.info("定时输出，当前时间为：" + timestamp);

		// 实例发送端-- 获取数据
		envMonitoring eM = new envMonitoring();
		// 接收结果集
		RequestGongWuShuTspRealTimeData r = new RequestGongWuShuTspRealTimeData();
		// 查找所有
		List<TspHaveDevCode> l = tspDetailedMapper.findAll();
		// 临时存储变量
		TspHaveDevCode tempClass = new TspHaveDevCode();
		// 临时存储变量
		String temp = "";
		String code = "";
		// 记录成功提交到工务署的条数
		int insertRecordNum = 0;

		for (int i = 0; i < l.size(); i++) {
			log.info("lsize" + l.size());
			tempClass = l.get(i);
			temp = tempClass.toString();
			code = tempClass.getDevice_code();
			if (temp == null)
				log.info("这里进入null：" + l.get(i));

			try {

				r = tspGetDataMapper.findRecentlyRealTimeOneSendGWS(code);
				log.info(r.toString());
			} catch (Exception e) {
				log.info("在表tspgetdata里没有该设备号的记录信息！请联系8806公司的工作人员。" + code);
				continue;
				// TODO: handle exception
			}

			// 插入条数

			String resultStr = eM.addRecord(r);
			JSONObject resultJsonObject;
			resultJsonObject = JSONObject.parseObject(resultStr);
			String message = resultJsonObject.getString("message");
			log.info("jsonObjectGetOneData-Message:" + message);
			if (message.equals("成功")) {
				log.info("陈工");
				insertRecordNum++;
			}

		}

		GeneralRecordNumBeans generalRecordNumBeans = new GeneralRecordNumBeans();
		log.info("一輪完成！进入mysql插入本次成功条数！");
		TimeUtil t = new TimeUtil();
		String currTime = t.timeUtil2String();
		generalRecordNumBeans.setRecord_data(currTime);
		generalRecordNumBeans.setRecord_num(insertRecordNum);
		recordNumMapper.innerOneRecord(generalRecordNumBeans);

	}

	/**
	 * web层，统筹数据 tspgetdata和tsp_detailed一起
	 * 以下皆为小方法start，不实现serviceimpl而是直接在方法写，所以这里就不重构方法了
	 * 
	 * @return
	 */
	public int FindGetDataTodayTspTotalNum() {
		return tspGetDataMapper.findTodayTspTotalNum();
	}

	// 查找本周内每天的上传详细汇总，list(0)是今天 list(1)是昨天 周几是list里面的对象.What_day_is_it_today
	public List<GeneralRecordNumBeans> weekURecord() {
		return recordNumMapper.weekURecord();
		// TODO Auto-generated method stub

	}

	// 查找本周内每天的获得详细汇总，list(0)是今天 list(1)是昨天 周几是list里面的对象.What_day_is_it_today
	public List<GeneralRecordNumBeans> findWeekToeveryDay() {

		return recordNumMapper.weekSRecord();

	}

	public int FindGetDataYesterdayTspTotalNum() {
		int resultNum = 0;
		try {
			resultNum = tspGetDataMapper.findYesterdayTspTotalNum();
		} catch (Exception e) {
			log.info("昨日记录为空，请注意general_record_numBeans的情况");
			return resultNum;
			// TODO: handle exception
		}
		return resultNum;
	}

	public int FindGetDataOneweekTspTotalNumAverage() {
		return tspGetDataMapper.findOneweekTspTotalNumAverage();
	}

	public int FindGetDataOnedayTspTotalNum(String data) {
		return tspGetDataMapper.findOnedayTspTotalNum(data);
	}

	// 查询已经上传到工务署的数据条数
	public int FindUploadGWSTodayTspTotalNum(int conditions) {
		// conditions参数说明：0是今天 1是昨天 2是前天 以此类推 详细请查看mapper层的sql
		int resultNum = 0;
		try {
			resultNum = recordNumMapper.findSomeByconditions(conditions);
		} catch (Exception e) {
			log.info("昨日或今日记录为空，请注意general_record_numBeans的情况");
			return resultNum;
			// TODO: handle exception
		}
		return resultNum;
	}

	public int FindAverageGWSToday() {
		// 该方法返回的是距今七天前到现在的七天数据查询平均值
		return recordNumMapper.findAverage();
	}

	/**
	 * 以上皆为小方法--end
	 * 
	 * @return
	 */

	public TspHaveDevCode SelectOne(String devcode) {
		return tspDetailedMapper.selectOne(devcode);
	}

}
